<template>
  <a-button type="primary" @click="handleClick">AI 生成题目</a-button>
  <a-drawer
    :width="340"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    unmountOnClose
  >
    <template #title>AI 生成题目</template>
    <div>
      <a-form :model="form" @submit="handleSubmit">
        <a-form-item label="应用id">
          {{ appId }}
        </a-form-item>
        <a-form-item label="题目数量">
          <a-input-number
            v-model="form.questionNumber"
            placeholder="请填入您生成的题目数量"
          />
        </a-form-item>
        <a-form-item label="选项数量">
          <a-input-number
            v-model="form.optionNumber"
            placeholder="请填入您生成的选项数量"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit">一键生成</a-button>
            <a-button type="primary" @click="doSSESubmit">实时生成</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import { defineProps, ref, withDefaults } from "vue";
import API from "@/api";
import { aiGenerateQuestionUsingPost } from "@/api/questionController";
import message from "@arco-design/web-vue/es/message";
import QuestionContentDTO = API.QuestionContentDTO;

interface Props {
  appId: string;
  onSuccess?: (result: API.QuestionContentDTO[]) => void;
  onSSESuccess?: (result: API.QuestionContentDTO) => void;
  onSSEStart?: (event: any) => void;
  onSSEClose?: (event: any) => void;
}

const props = withDefaults(defineProps<Props>(), {
  appId: () => {
    return "";
  },
});

const form = ref<API.AiGenerateQuestionRequest>({
  optionNumber: 0,
  questionNumber: 0,
});

const visible = ref(false);

const handleClick = () => {
  visible.value = true;
};
const handleOk = () => {
  visible.value = false;
};
const handleCancel = () => {
  visible.value = false;
};

const questionContentArray: QuestionContentDTO[] = [
  {
    title: "What is your favorite color?",
    options: [{ key: "Red", result: "red", score: 1, value: "red" }],
  },
];
const submitting = ref(false);
const handleSubmit = async () => {
  if (!props.appId) {
    return;
  }
  const res = await aiGenerateQuestionUsingPost({
    appId: props.appId as any,
    ...form.value,
  });
  if (res.data.code === 0 && res.data.data.length > 0) {
    if (props.onSuccess) {
      alert("生成题目成功，请查看详情页面");
      props.onSuccess(res.data.data);
    } else {
      message.success("生成题目成功");
    }
    // 关闭抽屉
    handleCancel();
  } else {
    message.error("操作失败，" + res.data.message);
  }
  submitting.value = false;
};

const sseSubmitting = ref(false);
const doSSESubmit = async () => {
  if (!props.appId) {
    return;
  }
  sseSubmitting.value = true;
  // 创建 SSE 请求
  const url =
    "http://localhost:48080/api/question/ai_generate/sse" +
    `?appId=${props.appId}&optionNumber=${form.value.optionNumber}&questionNumber=${form.value.questionNumber}`;

  const eventSource = new EventSource(url, { withCredentials: true });

  let first = true;
  // 接收消息
  eventSource.onmessage = function (event) {
    console.log("收到消息：", event.data);
    if (first) {
      props.onSSEStart?.(event);
      handleCancel();
      first = !first;
    }
    props.onSSESuccess?.(JSON.parse(event.data));
  };
  // 报错或连接关闭时触发
  eventSource.onerror = function (event) {
    if (event.eventPhase === EventSource.CLOSED) {
      console.log("关闭连接");
      props.onSSEClose?.(event);
      eventSource.close();
    } else {
      eventSource.close();
    }
  };
  sseSubmitting.value = false;
};
</script>
